package com.jinsp.startup_library;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * Created by luoshuai on 2/25/22
 * <p>
 * 实现startup，封装基本功能
 */
public abstract class AndroidStartup<T> implements Startup<T> {

    protected final List<Class<? extends Startup<?>>> dependenceList;
    private volatile CountDownLatch countDownLatch;

    public AndroidStartup() {
        dependenceList = new ArrayList<>();
    }

    @Override
    public List<Class<? extends Startup<?>>> getDependenceList() {
        return dependenceList;
    }

    @Override
    public int getDependenceCount() {
        return getDependenceList() == null ? 0 : getDependenceList().size();
    }

    @Override
    public void startWaiting() {
        if (countDownLatch == null) {
            countDownLatch = new CountDownLatch(getDependenceCount());
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void notifyAndRunning() {
        countDownLatch.countDown();
    }

    /**
     * 获取任务名
     *
     * @return 启动任务名
     */
    @Override
    public String getStartupName() {
        return getClass().getSimpleName();
    }
}
